<template>
  <view>
    <AddressBar
      show-default-icon
      show-right-icon
      :address-data="addressBar.data"
      :address-list="addressBar.list"
      @editAddressFn="handleChangeAddress"
    />
    <view class="list-bg">
      <YcIntegralProducts
        :product-details="[productDetail]"
      />
    </view>
    <view class="list-bg">
      <MenuCell
        :cell-data="integralCell.data"
        :cell-column="integralCell.column"
      />
    </view>
    <PageFooterBar
      btn-name="确认兑换"
      :info="footerInfo"
      @click="handleExchange"
    />
  </view>
</template>

<script>
import AddressBar from '@/components/ycAddressBar/address-bar'
import YcIntegralProducts from '@/components/yc-product-list/yc-integral-products'
import MenuCell from '@/components/menu-cell'
import PageFooterBar from '@/components/page-footer-bar'
import { getAddressList } from '@/api/address'
import { serachIntegralProductMsg, submitIntegralOrder, ownGoodsConfirm } from '@/api/yc_userInfo'
import { formatDate } from '@/common/common';
export default {
  name: 'ConfirmExchange',
  components: {
    AddressBar,
    YcIntegralProducts,
    MenuCell,
    PageFooterBar
  },
  data() {
    return {
      options: {},
      addressBar: {
        data: {},
        list: []
      },
      shippingAddressModel: {},
      productDetail: {},
      integralCell: {
        column: [],
        data: {}
      },
      cityCode:'',//查询需要销售区域字段
      warehouseCode:'',//查询需要仓
    }
  },
  onLoad(options) {
    // #ifdef MP-ALIPAY || MP-WEIXIN
    this.cityCode = this.vuex_cityInfo.cityCode
    this.warehouseCode =this.vuex_cityInfo.warehouseCode
    // #endif
    //#ifdef H5
    const mySelectStation =JSON.parse(localStorage.getItem('my_select_station'))
    this.cityCode = mySelectStation.cityCode
    this.warehouseCode =mySelectStation.warehouseCode
    // #endif  
    const { skuId, exchangeType } = options ?? {}
    this.options = { skuId, exchangeType }
    this.setIntegralCell()
    this.getReceiverAddresses()
    this.getProductDetails()
  },
  computed: {
    footerInfo() {
      const info = {
        label: this.options.exchangeType == 0 ? '应付积分' : '应付鑫币',
        value: this.options.exchangeType == 0 ? this.productDetail.needIntegral : this.productDetail.needCoin
      }
      return info
    }
  },
  watch: {
    shippingAddressModel(val) {
      this.addressBar.data = val
    }
  },
  methods: {
    //监听reFresh,如果有修改就执行监听器
    reFresh() { //如果没有地址 首次新增地址选择之后页面不显示 所以需要刷新调取地址方法来显示页面数据地址
      if (this.addressBar.list.length == 0) {
        this.getReceiverAddresses()
      }
    },
    setIntegralCell() {
      console.log('222', this.options.exchangeType)
      const cells = [
        { label: '支付方式', fields: ['payWay'] },
        { label: '配送方式', fields: ['deliveryWay'] }
      ]
      this.integralCell.column = cells.map(item => ({
        ...item,
        labelStyle: 'font-size: 24rpx;color: #666;',
        contentStyle: 'margin-right: 28rpx'
      }))
      if (this.options.exchangeType == 0) {
        this.integralCell.data = {
          payWay: '积分抵扣',
          deliveryWay: '快递'
        }
      } else {
        this.integralCell.data = {
          payWay: '鑫币抵扣',
          deliveryWay: '快递'
        }
      }
    },
    async getReceiverAddresses() {
      const { customerId, memberId } = this.vuex_memberInfo
      const params = {
        pageNum: 1,
        pageSize: 50,
        member_id: memberId,
        type: 10, // 10默认，20代客下单
        customer_id: customerId
      }
      const res = await getAddressList(params)
      this.addressBar.list = res?.list ?? []
      const defaultAddress = this.addressBar.list.find(item => item.is_default == 1)
      this.addressBar.data = defaultAddress ?? this.addressBar.list[0]
    },
    async getProductDetails() {
      const { memberId } = this.vuex_memberInfo
      const params = { ...this.options, memberId ,cityCode:this.cityCode,warehouseCode:this.warehouseCode }
      const res = await serachIntegralProductMsg(params)
      if (res.code == 0) {
        console.log('11111111')
    
        const refexchangeType ={exchangeType:this.options.exchangeType}
        this.productDetail = { ...res.data,...refexchangeType }
        console.log(this.productDetail)
      }
    },
    // 修改地址
    handleChangeAddress() {
      const shipAddId = this.addressBar.data?.ship_add_id ?? ''
      uni.navigateTo({
        url: `/address/addressList?type=order&id=${shipAddId}`
      })
    },
    // 确认兑换
    handleExchange() {
      const hasNoAddress = !this.addressBar.data || Object.keys(this.addressBar.data).length == 0
      if (hasNoAddress) {
        this.$u.toast('配送地址为空，请添加！')
      }
      this.confirmExchange()
    },
    async confirmExchange() {
      const payModel = {}
      if (this.options.exchangeType == 0) {
        payModel.payName = '积分抵扣'
        payModel.payType = 1601
      } else {
        payModel.payName = '鑫币抵扣'
        payModel.payType = 1602
      }

      const addressData = this.addressBar.data
      const adressObj = { //地址转为驼峰 传给提交接口
        addressPersonList: [
          {
            addressId: addressData.addressPersonList[0].addressId,
            id: addressData.addressPersonList[0].id,
            mobile: addressData.addressPersonList[0].mobile,
            receiverName: addressData.addressPersonList[0].receiverName,
            status: addressData.addressPersonList[0].status
          }
        ],
        areaName: addressData.areaName,
        cityCode: addressData.city_code,
        cityId: addressData.city_id,
        cityName: addressData.cityName,
        detailAddress: addressData.detail_address,
        districtCode: addressData.district_code,
        districtId: addressData.district_id,
        email: addressData.email,
        isDefault: addressData.is_default,
        lat: addressData.lat,
        lng: addressData.lng,
        officePhone: addressData.office_phone,
        provinceCode: addressData.province_code,
        provinceId: addressData.province_id,
        provinceName: addressData.provinceName,
        shipAddId: addressData.ship_add_id,
        streetCode: addressData.street_code,
        streetId: addressData.street_id,
        streetName: addressData.streetName,
        warehouseCode:this.warehouseCode
      }
      const params = {
        payModel,
        address: adressObj,
        deliverWay: 'kd', // 快递
        usedIntegral: this.options.exchangeType == 0 ? this.productDetail.needIntegral : this.productDetail.needCoin, // 兑换积分
        skuModel: {
          skuId: this.productDetail?.skuId,
          salePrice: this.options.exchangeType == 0 ? this.productDetail.needIntegral : this.productDetail.needCoin,
          buyCount: 1
        },
        exchangeType: this.options.exchangeType
      }
      if(this.productDetail.skuSource ==2){
        params.cityCode=this.cityCode
        params.warehouseCode =this.warehouseCode
      }
        //自有商品提交ownGoodsConfirm
      const res = this.productDetail.skuSource ==2? await ownGoodsConfirm(params):await submitIntegralOrder(params)
      if (res.code == 0) {
        const successInfo = {
          orderId: res.data.orderNo,
          needIntegral: this.options.exchangeType == 0 ? this.productDetail.needIntegral : this.productDetail.needCoin,
          deliverWay: 'kd',
          deliverWayStr: '快递',
          exchangeTime: this.getExchangeTime(),
          orderStatus: res.data.orderStatus,
          exchangeType: this.options.exchangeType
        }
        uni.redirectTo({ url: `/myAccount/pointsMall/exchangeSuccess?successInfo=${JSON.stringify(successInfo)}` })
      } else {
        this.$u.toast(res.msg)
      }
    },
    // 获取兑换时间
    getExchangeTime() {
      const time = new Date()
      const date = formatDate(time, 'yyyy-mm-dd') // 年-月-日
      const hours = time.getHours() // 时
      let minutes = time.getMinutes() // 分
      if (minutes > 0 && minutes < 10) minutes = '0' + minutes
      return `${date} ${hours}:${minutes}`
    }
  }
}
</script>
